<template>
  <div class="expense-list-page">
    <!-- 统计卡片 -->
    <div class="stats-card">
      <div class="stats-row">
        <div class="stats-item">
          <div class="stats-value">{{ stats.totalExpenses }}</div>
          <div class="stats-label">报销总数</div>
        </div>
        <div class="stats-item">
          <div class="stats-value">¥{{ formatAmount(stats.totalAmount) }}</div>
          <div class="stats-label">报销总额</div>
        </div>
        <div class="stats-item">
          <div class="stats-value">{{ stats.pendingCount }}</div>
          <div class="stats-label">待审批</div>
        </div>
        <div class="stats-item">
          <div class="stats-value">{{ stats.approvedCount }}</div>
          <div class="stats-label">已批准</div>
        </div>
      </div>
    </div>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <van-dropdown-menu>
        <van-dropdown-item v-model="filter.type" :options="typeOptions" />
        <van-dropdown-item v-model="filter.status" :options="statusOptions" />
        <van-dropdown-item title="时间范围" ref="dateDropdown">
          <div class="date-filter">
            <van-cell title="选择时间范围">
              <template #right-icon>
                <van-icon name="close" @click="resetDateFilter" />
              </template>
            </van-cell>
            <div class="date-range">
              <van-field
                readonly
                label="开始日期"
                :model-value="formatDate(filter.startDate)"
                placeholder="请选择开始日期"
                @click="showStartDatePicker = true"
              />
              <van-field
                readonly
                label="结束日期"
                :model-value="formatDate(filter.endDate)"
                placeholder="请选择结束日期"
                @click="showEndDatePicker = true"
              />
            </div>
            <div class="filter-buttons">
              <van-button plain block @click="resetDateFilter">重置</van-button>
              <van-button type="primary" block @click="applyDateFilter">确定</van-button>
            </div>
          </div>
        </van-dropdown-item>
      </van-dropdown-menu>
      
      <!-- 日期选择弹窗 -->
      <van-calendar v-model:show="showStartDatePicker" 
                   @confirm="onStartDateConfirm"
                   :show-confirm="true"
                   color="#1989fa"/>
                   
      <van-calendar v-model:show="showEndDatePicker" 
                   @confirm="onEndDateConfirm"
                   :show-confirm="true"
                   color="#1989fa"/>
    </div>
    
    <!-- 报销列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <template v-if="expenseList.length === 0 && !loading">
          <div class="empty-state">
            <van-empty image="search" description="暂无报销记录" />
            <van-button type="primary" icon="plus" size="small" class="empty-action" @click="addExpense">
              新增报销
            </van-button>
          </div>
        </template>
        
        <div v-else class="expense-list">
          <van-swipe-cell
            v-for="item in expenseList"
            :key="item.id"
            :before-close="beforeClose"
          >
            <van-cell clickable @click="viewDetail(item.id)">
              <template #title>
                <div class="expense-title">{{ item.title }}</div>
                <div class="expense-code">报销单号: {{ item.code }}</div>
              </template>
              <template #label>
                <div class="expense-info">
                  <div class="expense-date">{{ item.date }}</div>
                  <div class="expense-type">{{ getTypeName(item.type) }}</div>
                </div>
                <div class="expense-status-row">
                  <van-tag :type="getStatusType(item.status)" size="medium">
                    {{ getStatusText(item.status) }}
                  </van-tag>
                  <div class="expense-amount">¥{{ formatAmount(item.amount) }}</div>
                </div>
              </template>
            </van-cell>
            <template #right>
              <van-button
                v-if="item.status === 'pending'"
                square
                text="撤销"
                type="danger"
                class="swipe-button"
                @click="cancelExpense(item.id)"
              />
              <van-button
                square
                text="查看"
                type="primary"
                class="swipe-button"
                @click="viewDetail(item.id)"
              />
            </template>
          </van-swipe-cell>
        </div>
      </van-list>
    </van-pull-refresh>
    
    <!-- 新增按钮 -->
    <div class="action-buttons">
      <van-button 
        icon="plus" 
        type="primary" 
        round 
        size="small" 
        @click="addExpense" 
        class="action-button"
      >
        新增报销
      </van-button>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { 
  NavBar, DropdownMenu, DropdownItem, Cell, Icon, Calendar,
  Button, Field, List, PullRefresh, Tag, Empty,
  SwipeCell, Dialog, Toast
} from 'vant'

export default {
  name: 'MobileFinanceExpense',
  components: {
    vanNavBar: NavBar,
    vanDropdownMenu: DropdownMenu,
    vanDropdownItem: DropdownItem,
    vanCell: Cell,
    vanIcon: Icon,
    vanCalendar: Calendar,
    vanButton: Button,
    vanField: Field,
    vanList: List,
    vanPullRefresh: PullRefresh,
    vanTag: Tag,
    vanEmpty: Empty,
    vanSwipeCell: SwipeCell
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    const dateDropdown = ref(null)
    
    // 列表状态
    const loading = ref(false)
    const refreshing = ref(false)
    const finished = ref(false)
    const expenseList = ref([])
    const page = ref(1)
    const pageSize = ref(10)
    
    // 统计数据
    const stats = reactive({
      totalExpenses: 0,
      totalAmount: 0,
      pendingCount: 0,
      approvedCount: 0
    })
    
    // 筛选条件
    const filter = reactive({
      type: 'all',
      status: 'all',
      startDate: '',
      endDate: ''
    })
    
    // 日期选择器状态
    const showStartDatePicker = ref(false)
    const showEndDatePicker = ref(false)
    
    // 下拉选项
    const typeOptions = [
      { text: '全部类型', value: 'all' },
      { text: '差旅费', value: 'travel' },
      { text: '办公用品', value: 'office' },
      { text: '会议费', value: 'meeting' },
      { text: '交通费', value: 'transport' },
      { text: '其他', value: 'other' }
    ]
    
    const statusOptions = [
      { text: '全部状态', value: 'all' },
      { text: '待审批', value: 'pending' },
      { text: '已批准', value: 'approved' },
      { text: '已拒绝', value: 'rejected' },
      { text: '已付款', value: 'paid' }
    ]
    
    // 计算统计数据
    const calculateStats = () => {
      // 使用全部数据（不考虑分页）
      const allData = mockExpenseData
      
      stats.totalExpenses = allData.length
      stats.totalAmount = allData.reduce((total, item) => total + item.amount, 0)
      stats.pendingCount = allData.filter(item => item.status === 'pending').length
      stats.approvedCount = allData.filter(item => item.status === 'approved').length
    }
    
    // 获取报销列表数据
    const fetchExpenseList = (isRefresh = false) => {
      if (isRefresh) {
        page.value = 1
        finished.value = false
        expenseList.value = []
      }
      
      loading.value = true
      
      // 实际应用中应该调用 store.dispatch 获取数据
      // 例如: store.dispatch('finance/getExpenseList', { page: page.value, ...filter })
      
      // 模拟API请求
      setTimeout(() => {
        const newItems = generateMockData(page.value, pageSize.value, filter)
        if (isRefresh) {
          expenseList.value = newItems
        } else {
          expenseList.value = [...expenseList.value, ...newItems]
        }
        
        loading.value = false
        if (refreshing.value) refreshing.value = false
        
        // 判断是否还有更多数据
        if (newItems.length < pageSize.value) {
          finished.value = true
        } else {
          page.value += 1
        }
      }, 1000)
    }
    
    // 生成模拟数据
    const generateMockData = (page, pageSize, filter) => {
      const result = []
      const startIndex = (page - 1) * pageSize
      
      // 根据筛选条件过滤
      let filteredData = [...mockExpenseData]
      
      if (filter.type !== 'all') {
        filteredData = filteredData.filter(item => item.type === filter.type)
      }
      
      if (filter.status !== 'all') {
        filteredData = filteredData.filter(item => item.status === filter.status)
      }
      
      if (filter.startDate && filter.endDate) {
        const start = new Date(filter.startDate).getTime()
        const end = new Date(filter.endDate).getTime()
        
        filteredData = filteredData.filter(item => {
          const itemDate = new Date(item.date).getTime()
          return itemDate >= start && itemDate <= end
        })
      }
      
      // 返回当前页数据
      for (let i = startIndex; i < startIndex + pageSize && i < filteredData.length; i++) {
        result.push(filteredData[i])
      }
      
      return result
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
    
    // 格式化金额
    const formatAmount = (amount) => {
      return parseFloat(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        pending: '待审批',
        approved: '已批准',
        rejected: '已拒绝',
        paid: '已付款'
      }
      return statusMap[status] || status
    }
    
    // 获取状态对应的类型
    const getStatusType = (status) => {
      const typeMap = {
        pending: 'primary',
        approved: 'success',
        rejected: 'danger',
        paid: 'warning'
      }
      return typeMap[status] || 'default'
    }
    
    // 获取类型名称
    const getTypeName = (type) => {
      const typeMap = {
        travel: '差旅费',
        office: '办公用品',
        meeting: '会议费',
        transport: '交通费',
        other: '其他'
      }
      return typeMap[type] || type
    }
    
    // 日期筛选相关方法
    const onStartDateConfirm = (date) => {
      filter.startDate = date
      showStartDatePicker.value = false
      if (!filter.endDate) {
        showEndDatePicker.value = true
      }
    }
    
    const onEndDateConfirm = (date) => {
      filter.endDate = date
      showEndDatePicker.value = false
    }
    
    const resetDateFilter = () => {
      filter.startDate = ''
      filter.endDate = ''
    }
    
    const applyDateFilter = () => {
      if (dateDropdown.value) {
        dateDropdown.value.toggle(false)
        // 应用筛选后刷新列表
        fetchExpenseList(true)
      }
    }
    
    // SwipeCell 滑动操作
    const beforeClose = ({ position, instance }) => {
      switch (position) {
        case 'right':
          instance.close()
          break
        case 'cell':
          instance.close()
          break
      }
    }
    
    // 加载更多
    const onLoad = () => {
      fetchExpenseList()
    }
    
    // 下拉刷新
    const onRefresh = () => {
      finished.value = false
      fetchExpenseList(true)
    }
    
    // 查看详情
    const viewDetail = (id) => {
      router.push(`/new/finance/expense/${id}`)
    }
    
    // 撤销报销
    const cancelExpense = (id) => {
      Dialog.confirm({
        title: '确认操作',
        message: '确定要撤销该报销申请吗？',
      })
      .then(() => {
        Toast.success('已撤销')
        
        // 更新本地数据
        const index = expenseList.value.findIndex(item => item.id === id)
        if (index !== -1) {
          expenseList.value[index].status = 'rejected'
        }
      })
      .catch(() => {
        // 取消操作
      })
    }
    
    // 新增报销
    const addExpense = () => {
      router.push('/new/finance/reimbursement/form')
    }
    
    // 监听筛选条件变化
    const watchFilter = () => {
      // 当类型或状态变化时刷新列表
      for (const key of ['type', 'status']) {
        watch(() => filter[key], () => {
          fetchExpenseList(true)
        })
      }
    }
    
    onMounted(() => {
      fetchExpenseList()
      calculateStats()
      watchFilter()
    })
    
    // 模拟数据
    const mockExpenseData = [
      {
        id: 1,
        title: '项目启动会议费用',
        code: 'EXP202310280001',
        type: 'meeting',
        status: 'approved',
        date: '2023-10-28',
        amount: 1280.50
      },
      {
        id: 2,
        title: '客户拜访交通费',
        code: 'EXP202310270002',
        type: 'transport',
        status: 'pending',
        date: '2023-10-27',
        amount: 326.50
      },
      {
        id: 3,
        title: '办公用品采购',
        code: 'EXP202310250003',
        type: 'office',
        status: 'paid',
        date: '2023-10-25',
        amount: 459.80
      },
      {
        id: 4,
        title: '市场调研差旅费',
        code: 'EXP202310230004',
        type: 'travel',
        status: 'rejected',
        date: '2023-10-23',
        amount: 2680.00
      },
      {
        id: 5,
        title: '培训会议餐费',
        code: 'EXP202310200005',
        type: 'meeting',
        status: 'approved',
        date: '2023-10-20',
        amount: 860.00
      },
      {
        id: 6,
        title: '出差住宿费用',
        code: 'EXP202310180006',
        type: 'travel',
        status: 'pending',
        date: '2023-10-18',
        amount: 1560.00
      },
      {
        id: 7,
        title: '商务接待费用',
        code: 'EXP202310150007',
        type: 'other',
        status: 'paid',
        date: '2023-10-15',
        amount: 3280.50
      },
      {
        id: 8,
        title: '打印机耗材',
        code: 'EXP202310120008',
        type: 'office',
        status: 'approved',
        date: '2023-10-12',
        amount: 358.60
      },
      {
        id: 9,
        title: '软件服务年费',
        code: 'EXP202310100009',
        type: 'other',
        status: 'approved',
        date: '2023-10-10',
        amount: 5680.00
      },
      {
        id: 10,
        title: '员工通勤补贴',
        code: 'EXP202310050010',
        type: 'transport',
        status: 'pending',
        date: '2023-10-05',
        amount: 1200.00
      },
      {
        id: 11,
        title: '参展费用',
        code: 'EXP202310010011',
        type: 'meeting',
        status: 'rejected',
        date: '2023-10-01',
        amount: 12800.00
      },
      {
        id: 12,
        title: '业务培训费',
        code: 'EXP202309280012',
        type: 'other',
        status: 'paid',
        date: '2023-09-28',
        amount: 4580.00
      },
      {
        id: 13,
        title: '快递费用',
        code: 'EXP202309250013',
        type: 'office',
        status: 'approved',
        date: '2023-09-25',
        amount: 126.50
      },
      {
        id: 14,
        title: '市内交通费',
        code: 'EXP202309220014',
        type: 'transport',
        status: 'approved',
        date: '2023-09-22',
        amount: 258.00
      },
      {
        id: 15,
        title: '项目验收餐费',
        code: 'EXP202309200015',
        type: 'meeting',
        status: 'pending',
        date: '2023-09-20',
        amount: 960.50
      }
    ]
    
    return {
      loading,
      refreshing,
      finished,
      expenseList,
      filter,
      typeOptions,
      statusOptions,
      dateDropdown,
      showStartDatePicker,
      showEndDatePicker,
      formatDate,
      formatAmount,
      getStatusText,
      getStatusType,
      getTypeName,
      onStartDateConfirm,
      onEndDateConfirm,
      resetDateFilter,
      applyDateFilter,
      beforeClose,
      onLoad,
      onRefresh,
      viewDetail,
      cancelExpense,
      addExpense,
      stats
    }
  }
}
</script>

<style scoped>
.expense-list-page {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 70px;
}

.stats-card {
  background-color: #fff;
  margin: 12px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1px;
  background-color: #f5f5f5;
}

.stats-item {
  padding: 12px 0;
  text-align: center;
  background-color: #fff;
}

.stats-value {
  font-size: 18px;
  font-weight: 500;
  color: #1989fa;
  margin-bottom: 4px;
}

.stats-label {
  font-size: 12px;
  color: #969799;
}

.filter-section {
  position: sticky;
  top: 46px;
  z-index: 10;
}

.date-filter {
  padding: 16px 16px 0;
}

.date-range {
  margin-bottom: 16px;
}

.filter-buttons {
  display: flex;
  padding: 0 16px 16px;
  gap: 12px;
}

.expense-list {
  margin-top: 8px;
}

.expense-title {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 4px;
}

.expense-code {
  font-size: 12px;
  color: #969799;
}

.expense-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.expense-date, .expense-type {
  font-size: 12px;
  color: #646566;
}

.expense-status-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.expense-amount {
  font-weight: 500;
  color: #1989fa;
}

.swipe-button {
  height: 100%;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.empty-action {
  margin-top: 16px;
}

.action-buttons {
  position: fixed;
  right: 20px;
  bottom: 80px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.action-button {
  width: auto;
  height: 40px;
  box-shadow: 0 2px 8px rgba(25, 137, 250, 0.3);
}

/* 适配暗黑模式 */
@media (prefers-color-scheme: dark) {
  .expense-list-page {
    background-color: #000;
  }
  
  .stats-card {
    background-color: #1c1c1e;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }
  
  .stats-row {
    background-color: #2c2c2e;
  }
  
  .stats-item {
    background-color: #1c1c1e;
  }
  
  .expense-code,
  .expense-date,
  .expense-type {
    color: #7d7e80;
  }
}
</style> 